package com.baoy.cloud.xxx.common.ex;

import com.baoy.cloud.xxx.common.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;

@Slf4j
@ControllerAdvice
public class ControllerExceptionHandler {


    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public JSONResult handlerException(Exception e) {
        log.error("{}", e);
        return JSONResult.writeFailure(Exceptions.failure.getCode(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public JSONResult handlerMethodArgumentException(MethodArgumentNotValidException e) {

        StringBuffer errorMsg = new StringBuffer();
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        for (int i = 0; i < errors.size(); i++) {
            errorMsg.append(errors.get(i).getDefaultMessage() + ",");
        }
        String errMsg = errorMsg.toString();
        log.error(">>>>接口参数验证失败：{}", errMsg);
        return JSONResult.writeFailure(Exceptions.failure.getCode(), errMsg);
    }


}